import { t } from 'i18next'
import { useEffect, useMemo, useRef } from 'react'
import shallow from 'zustand/shallow'
import { terminalEntity, ListTranslator } from './translator'
import { differenceBy, findIndex } from 'lodash-es'
import { Alert, confirmModal } from '@/components/Alert'
import { InnerInputRef, Message, Modal } from '@kedacom/react-next'
import { usePollStore } from './store'
import { ListTopActionItem } from '@/components/List'
import {
	fetchGetPollPlanList,
	fetchDeletePollPlan,
	fetchGetPollPlanDetail,
	fetchStartMeetingPollAndMangerPollCheck,
	fetchUpdatePollState,
	fetchGetPollInfo,
	fetchStartPoll,
	fetchStopRollCall,
	fetchAddPollPlan,
	fetchUpdatePollPlan,
} from '@/api/manager/poll'
import { useMccStore } from '../../store'
import { MtEntity } from '@/api/manager/mt'
import { DropData } from '@/api/manager/type'
import { PollEntity } from '@/api/manager/poll/interface'
import useLock from '@/hooks/useLock'
import { actionButtonsCancel } from '../../store.actionButton'
export const useData = () => {
	const meetingMoid = useMccStore((state) => state.mccInfo.meetingMoid)
	const {
		list,
		update,
		state,
		unlimited,
		poll_mode,
		planOptions,
		preName,
		planValue,
		keep_time,
		cur_poll_mt,
		isEdit,
		getCurList,
		getPara,
		saveStartList,
		checkPara,
		ws_mcc_meeting_poll,
		name,
		ws_mcc_meeting_up_poll,
		getPlanPara,
		num,
		mode,
	} = usePollStore(
		(state) => ({
			list: state.list,
			mode: state.mode,
			state: state.state,
			num: state.num,
			unlimited: state.unlimited,
			poll_mode: state.poll_mode,
			planOptions: state.planOptions,
			preName: state.preName,
			planValue: state.planValue,
			isUpload: state.is_upload,
			keep_time: state.keep_time,
			cur_poll_mt: state.cur_poll_mt,
			isEdit: state.isEdit,
			name: state.name,
			ws_mcc_meeting_poll: state.ws_mcc_meeting_poll,
			ws_mcc_meeting_up_poll: state.ws_mcc_meeting_up_poll,
			update: state.update,
			getCurList: state.getCurList,
			getPara: state.getPara,
			saveStartList: state.saveStartList,
			checkPara: state.checkPara,
			getPlanPara: state.getPlanPara,
		}),
		shallow
	)
	const inputRef = useRef<InnerInputRef>(null)
	const topActions: ListTopActionItem[] = [
		{
			text: t('删除'),
			onClick: () => {
				/**不能删除当前轮询终端和最后一个终端 */
				const unCheckedList = list.filter((l) => !l.status.checked)
				const checkedList = list.filter((l) => l.status.checked)
				/**(1) 未选择人员 (2) 轮询列表存在终端*/
				if (checkedList.length === 0 && list.length !== 0) {
					Alert(t('请选择人员'))
					return false
				}
				/**轮询状态中删除全部轮询终端*/
				if (checkedList.length === unCheckedList.length && state === 1) {
					Alert(t('正在轮询的终端不可删除。'))
					return false
				}
				/**(1)轮询中 (2)且正在轮询的终端处于被移除列表 */
				const flag = checkedList.some((l) => {
					return l.mcc.mtKey === cur_poll_mt?.mt_key && state === 1
				})
				if (flag) {
					Alert(t('正在轮询的终端不可删除。'))
					return false
				}
				update({ list: unCheckedList })
				getCurList()
				saveStartList(false)
			},
		},
		{
			text: t('清空'),
			onClick: () => {
				if (state === 1) {
					confirmModal({
						msg: t('您确定要清空当前轮询列表吗？'),
						onOk: async () => {
							const unCheckedList = list.filter((l) => l.mtKey === cur_poll_mt?.mt_key)
							update({ list: unCheckedList })
							getCurList()
							saveStartList()
						},
					})
					return
				} else {
					update({ list: [], _start: '' })
					getCurList()
					saveStartList()
				}
			},
		},
	]
	/**轮询次数的输入框*/
	const keepTimedisabled = useMemo(() => Boolean(state === 1 || state === 2 || unlimited), [state, unlimited])
	/**轮询状态下禁止操作*/
	const disabled = useMemo(() => Boolean(state === 1 || state === 2), [state])
	/**标题*/
	useEffect(() => {
		switch (poll_mode) {
			case 1:
				update({ poll_mode_text: t('会议轮询') })
				break
			case 2:
				update({ poll_mode_text: t('管理方轮询') })
				break
			case 3:
				update({ poll_mode_text: t('上传轮询') })
				break
		}
	}, [poll_mode])
	/**根据轮询间隔时间确定是自定义输入时间*/
	useEffect(() => {
		switch (keep_time) {
			case 15:
				update({ pollIntervalOptionsVal: '15' })
				break
			case 30:
				update({ pollIntervalOptionsVal: '30' })
				break
			case 60:
				update({ pollIntervalOptionsVal: '60' })
				break
			default:
				update({ pollIntervalOptionsVal: '0' })
				break
		}
	}, [keep_time])
	/**根据全局的设置的预案名称/电视墙预案列表获取选中的值*/
	useEffect(() => {
		var value = planOptions.find((item) => item.label === preName)?.value ?? '0'
		update({ planValue: value })
	}, [preName, planOptions])
	useEffect(() => {
		console.log('处理***(会议轮询、管理方轮询)', ws_mcc_meeting_poll)
		let _source_data = ws_mcc_meeting_poll
		if (!_source_data) return
		if (poll_mode === 1 && 1 === _source_data.type /**会议轮询*/) {
			let _data = _source_data || {}
			pollHandle(_source_data)
			if (_data.state !== 0 && _source_data?.state === 0) {
				update({
					unlimited: _data.num === 0 ? true : false,
					num: _data.num === 0 ? undefined : _data.num,
					mode: _data.mode,
				})
			}
		}
		if (poll_mode === 2 && 2 === _source_data.type /**管理方轮询*/) {
			let _data = _source_data || {}
			pollHandle(_source_data)
			if (_data.state !== 0 && _source_data?.state === 0) {
				update({
					unlimited: _data.num === 0 ? true : false,
					num: _data.num === 0 ? undefined : _data.num,
					mode: _data.mode,
				})
			}
		}
	}, [ws_mcc_meeting_poll])
	useEffect(() => {
		console.log('处理***上传轮询', ws_mcc_meeting_up_poll)
		let _source_data = ws_mcc_meeting_up_poll
		if (!_source_data) return
		if (poll_mode === 3) {
			const _data = _source_data || {}
			pollHandle(_source_data)
			if (_data.state !== 0 && _source_data?.state === 0) {
				update({
					unlimited: _data.num === 0 ? true : false,
					num: _data.num === 0 ? undefined : _data.num,
					mode: _data.mode,
				})
			}
		}
	}, [ws_mcc_meeting_up_poll])
	/**初始化加载数据*/
	useEffect(() => {
		loadPollData()
	}, [])
	/**请求轮询数据*/
	const loadPollData = async () => {
		let res = await fetchGetPollInfo(meetingMoid, poll_mode)
		if (res.success) {
			/**轮询状态0 空闲 1轮询中 2暂停*/
			if (res.data && res.data.state === 0) {
				return
			}
			const pollData = res.data ?? null
			pollHandle(pollData)
			loadPlanData()
		} else {
			Alert(res.description || t('获取轮询信息失败'))
		}
	}
	/**处理数据会议的轮询数据*/
	const pollHandle = (pollData: PollEntity | null) => {
		if (isEdit) {
			return false
		}
		if (!pollData) {
			setNOdata()
			return false
		}
		update({
			preName: pollData.name || t('不使用预案'),
			state: pollData.state || 0,
		})
		renderPollData(pollData)
	}
	/**设置轮询无数据的情况*/
	const setNOdata = () => {
		update({ preName: '' })
		renderPollData(null)
		// TS.mcc.setList.controller.clearList(that.$pollList)
		getCurList()
	}
	/**渲染轮询数据*/
	const renderPollData = (data: PollEntity | null) => {
		/**处理状态state*/
		if (data && JSON.stringify(data) !== '{}') {
			/**暂停 轮询 状态 */
			const _state_flag = Number(data.state) === 1 || Number(data.state) === 2 ? true : false
			/**轮询到的终端存在*/
			const _cur_poll_mt_flag = data.cur_poll_mt && data.cur_poll_mt.mt_id ? true : false
			/**因为停止轮询的时候仅会推送过来一个state状态为0 */
			if (data.hasOwnProperty('num')) {
				update({ unlimited: data.num === 0 ? true : false, num: data.num === 0 ? undefined : data.num })
			} else {
				update({
					unlimited: num === 0 || num === undefined ? true : false,
					num: num === 0 || num === undefined ? undefined : num,
				})
			}
			update({
				state: data.state ?? 0,
				keep_time: data.keep_time || keep_time,
				mode: data.mode ?? mode,
				list: data.state !== 0 ? ListTranslator(data.members || []) : list,
				cur_poll_mt: _state_flag && _cur_poll_mt_flag ? data.cur_poll_mt : null,
			})
			getCurList()
		} else {
			update({
				state: 0,
				keep_time: 30,
				num: undefined,
				unlimited: true,
				list: [],
				cur_poll_mt: null,
				preName: '',
				mode: 1,
			})
		}
	}
	/**加载预案 */
	const loadPlanData = async (planName?: string) => {
		const res = await fetchGetPollPlanList(meetingMoid)
		if (res.success && res.data) {
			const planData = res.data
			let arr = planData ? planData.map((item) => ({ label: item.name, value: item.id })) : []
			arr.unshift({ label: t('不使用预案'), value: '0' })
			update({ planOptions: arr })
			/**新增预案,更新预案(刷新预案列表)*/
			planName && update({ preName: planName })
		} else {
			Alert(res.description || t('获取轮询预案失败'))
		}
	}
	//拖拽
	const handleDrop = (dataTransfer: DropData, index: number) => {
		if (dataTransfer && dataTransfer.data && dataTransfer.data.mt) {
			let mt = dataTransfer.data.mt
			let from = dataTransfer.from
			let isMt = mt.isMt
			if (isMt || mt.conf_level === 1 || (!isMt && mt.online)) {
				if (!isMt) {
					Alert(t('会议不能进入轮询列表'))
					return
				}
				if (poll_mode === 2) {
					/**管理方轮询 */
					if ((mt as MtEntity).chairman === 1) {
						Alert(t('管理方不能加入管理方轮询列表'))
						return false
					}
				}
				if (poll_mode === 3) {
					/**上传轮询*/
					if (!isMt || Number(mt.conf_level) !== 2) {
						return
					}
				}
				dealDrop({
					mts: ListTranslator([mt as MtEntity]),
					from: dataTransfer.from,
					dropIndex: index,
				})
			}
		}
	}
	//拖拽进入列表
	const dealDrop = ({ mts, from, dropIndex }: terminalEntity) => {
		if (from !== 'poll') {
			const insertList = differenceBy(mts, list, (x) => x.mtKey)
			let newList = [...list.slice(0, dropIndex), ...insertList, ...list.slice(dropIndex)]
			update({ list: newList })
		} else {
			const baseList = differenceBy(list, mts, (x) => x.mtKey)
			let insertToBaseIndex = dropIndex
			const baseListMtKeys = baseList.map((l) => l.mtKey)
			const nextFirstBaseListIndex = findIndex(list, (l) => baseListMtKeys.includes(l.mtKey), dropIndex)
			if (nextFirstBaseListIndex === -1) {
				insertToBaseIndex = baseList.length
			} else {
				insertToBaseIndex = baseList.findIndex((l) => l.mtKey === list[nextFirstBaseListIndex].mtKey)
			}
			update({
				list: [...baseList.slice(0, insertToBaseIndex), ...mts, ...baseList.slice(insertToBaseIndex)],
			})
		}
		poll_mode === 1 && getCurList()
		saveStartList()
	}
	/**点击终端选项删除*/
	const handleRemoveMt = (mtKey: string) => {
		if ((cur_poll_mt?.mt_key === mtKey || list.length === 1) && state === 1) {
			Alert(t('正在轮询的终端不可删除。'))
			return
		}
		const unRemove = list.filter((l) => l.mtKey !== mtKey)
		update({ list: unRemove })
		if (useMccStore.getState().curPage === 'meeting_poll') {
			getCurList()
		}
		saveStartList()
	}
	/**双击轮询成员 */
	const handleClickLi = () => {
		state === 0 && startPoll()
		state === 1 && saveStartList(true)
		state === 2 && resumePoll()
	}
	/**清空终端*/
	const clear = () => {
		update({
			_start: '',
			list: [],
		})
	}
	/**开始轮询*/
	const startPoll = useLock(async () => {
		if (!checkPara(false)) {
			return
		}
		if (poll_mode === 2 || poll_mode === 1) {
			const res = await fetchStartMeetingPollAndMangerPollCheck(meetingMoid)
			if (res.success) {
				/**检测轮询开启(接口成功)*/
				if (res.data && res.data.poll_is_on) {
					/**点名轮询开启*/
					let str = poll_mode === 1 ? t('会议轮询') : t('管理方轮询')
					confirmModal({
						msg: t('点名轮询已开启，与{{name}}冲突。确定要关闭点名轮询，开启{{name}}', { name: str }),
						onOk: async () => {
							stopRollCallRequest()
						},
					})
				} else {
					startPollRequest()
				}
			} else {
				/**检测轮询开启(接口失败)*/
				Alert(res.description || t('开启轮询失败'))
				return false
			}
		} else {
			startPollRequest()
		}
	}, 100000)
	/**开始轮询(会议、管理方、上传)接口请求*/
	const startPollRequest = async () => {
		const params = getPara()
		const type = poll_mode
		const success = await fetchStartPoll(meetingMoid, type, params)
		!success && Alert(t('开始轮询操作失败'))
	}
	/**停止点名轮询*/
	const stopRollCallRequest = async () => {
		const success = await fetchStopRollCall(meetingMoid)
		success ? startPollRequest() : Alert(t('结束点名轮询失败'))
	}
	/**停止轮询 */
	const stopPoll = useLock(async () => {
		const type = poll_mode
		const success = await fetchUpdatePollState(meetingMoid, type, 0)
		!success && Alert(t('结束轮询失败'))
	})
	/**暂停轮询 */
	const pausePoll = useLock(async () => {
		const type = poll_mode
		const success = await fetchUpdatePollState(meetingMoid, type, 1)
		!success && Alert(t('暂停轮询失败'))
	})
	/**继续轮询 */
	const resumePoll = useLock(async () => {
		if (!checkPara(false)) {
			return
		}
		const type = poll_mode
		const success = await fetchUpdatePollState(meetingMoid, type, 2)
		!success && Alert(t('继续轮询失败'))
	})
	/**返回操作*/
	const handleReturnBack = () => {
		useMccStore.getState().setCurPage('mcc_main')
		actionButtonsCancel()
	}
	/**点击保存预案(清空输入框名称/打开模态框)*/
	const savePlan = async () => {
		if (!checkPara(true)) {
			return
		}
		planValue === '0' ? update({ name: '', isSavePlanOpen: true }) : updatePlan()
	}
	/**更新预案*/
	const updatePlan = useLock(async () => {
		const params = getPlanPara(true)
		const res = await fetchUpdatePollPlan(meetingMoid, planValue, params)
		res.success ? Message.info(t('预案保存成功')) : Alert(res.description || t('预案保存失败'))
		res.success && loadPlanData(preName)
	})
	/**新增预案*/
	const addPlan = useLock(async () => {
		const params = getPlanPara(false)
		let valid = await inputRef.current?.valid()
		if (!valid) return
		const res = await fetchAddPollPlan(meetingMoid, params)
		if (res.success) {
			loadPlanData(name)
			Message.info(t('预案保存成功'))
			update({ isSavePlanOpen: false })
		} else {
			Alert(res.description || t('预案保存失败'))
		}
	})
	/**切换预案*/
	const changePlan = async (value: string) => {
		const item = planOptions.find((item) => item.value === value)
		update({ planValue: value, preName: item?.label })
		if (value !== '0') {
			const res = await fetchGetPollPlanDetail(meetingMoid, value)
			res.success && Message.info(t('预案载入成功')) && renderPollData(res)
			!res.success && Alert(t('获取轮询预案失败'))
		} else {
			setNOdata()
		}
	}
	/**删除预案 */
	const deletePlan = async (item: { label: string; value: string }) => {
		/**判断删除的预案是否是当前选中的*/
		let isCur = planValue === item.value ? true : false
		let _plan_option = planOptions.filter((v) => item.value !== v.value)
		confirmModal({
			msg: t('是否确定删除{{name}}？', { name: item.label }),
			onOk: async () => {
				const res = await fetchDeletePollPlan(meetingMoid, item.value)
				if (res.success) {
					isCur && update({ preName: t('不使用预案'), planOptions: _plan_option })
					!isCur && update({ planOptions: _plan_option })
				} else {
					Alert(res.description || t('预案删除失败'))
				}
			},
		})
	}
	return {
		inputRef,
		/**轮询次数输入框是否disabled 轮询状态1轮询中 2暂停 勾选不限次数*/
		keepTimedisabled,
		/** 轮询状态1轮询中 2暂停*/
		disabled,
		/**加载预案数据 */
		loadPlanData,
		/**切换预案 */
		changePlan,
		/**删除预案 */
		deletePlan,
		handleDrop,
		clear,
		/**开始轮询 */
		startPoll,
		/**结束轮询 */
		stopPoll,
		/**暂停轮询 */
		pausePoll,
		/**返回操作设置主页 */
		handleReturnBack,
		/**保存预案 */
		savePlan,
		/**继续轮询 */
		resumePoll,
		/**操作按钮*/
		topActions,
		/**手动删除终端 */
		handleRemoveMt,
		/**新增预案 */
		addPlan,
		/**双击轮询成员 */
		handleClickLi,
	}
}
